package cloudspace.vm.io.console;

import java.util.LinkedList;
import java.util.List;

import org.zkoss.lang.Threads;
import org.zkoss.zk.ui.Desktop;
import org.zkoss.zk.ui.DesktopUnavailableException;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.util.Clients;

import cloudspace.vm.VM;

/**
 * This is the comet update thread. It constantly queries the Console looking
 * for updates to any of the registered streams. If an update is detected the
 * parent Component is notified.
 */
public class CometUpdateThread extends Thread
{
	Console console;
	/** The threads Component Parent */
	ConsoleLines parent;

	/** The thread running. */
	boolean threadRunning;
	List<CometEventListener> listeners;
	/** The desktop of the parent component */
	Desktop parentDesktop;
	VM context;
	String desktopID;

	/**
	 * Instantiates a new comet update thread.
	 * 
	 * @param userParent
	 *            the master Console Component
	 * @param userDesktop
	 *            The master desktop
	 */
	public CometUpdateThread(Desktop userDesktop)
	{
		context = VM.currentVM();
		desktopID = context.getDesktopID();
		threadRunning = true;
		parentDesktop = userDesktop;
		this.setName("CometUpdateThread");
		listeners = new LinkedList<CometEventListener>();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Thread#run()
	 */
	public void run()
	{
		context.registerThread();
		VM.setDesktopID(desktopID);
		try
		{

			while (threadRunning)
			{

				Threads.sleep(1000);
				try
				{
					if (parentDesktop.isServerPushEnabled())
					{
						Executions.activate(parentDesktop);
						Clients.showBusy("Loading Console", true);
						for (CometEventListener eListener : listeners)
						{
							eListener.checkEvent();
						}
						Clients.showBusy(null, false);
						Executions.deactivate(parentDesktop);
					}
				}
				catch (DesktopUnavailableException e)
				{
					;
				}
				catch (InterruptedException e)
				{
					;
				}

			}
		}
		finally
		{
			VM.deregisterThread();
		}
	}

	/**
	 * Sets the thread as finished so it will kill itself.
	 */
	public void setDone()
	{
		threadRunning = false;
	}

	/**
	 * Adds a listener to the CometUpdateThread. This listener will be checked
	 * during the normal run sequence.
	 * 
	 * @param cel
	 *            the event listener to add to the comet thread.
	 */
	public void addListener(CometEventListener cel)
	{
		listeners.add(cel);
	}

}
